class Event < ActiveRecord::Base
  has_many :traces
  has_many :tasks  

  validates_presence_of :title, :client, :description
  validates_format_of :ticketNumber, :with => /[0-9]+/, :on => :save

  before_destroy :removeTraces
  
  # Get distinct list of 15 events with the latest traces recorded.
  def self.getLatestEvents
    #@events = Event.find(:all,:order => "created_at DESC", :limit => 15)
    @events = Array.new()
    Trace.find(:all, :select => :event_id, :order => "created_at DESC", :group => :event_id, :limit => 15).each do |e|
      @events << Event.find(e.event_id)
    end
    return @events
  end
  
  def totalTime
    self.getTraces.sum(&:minSpent)
  end

  def getTraces
    return self.traces.sort { |a,b| b.created_at <=> a.created_at }
  end
  
  def removeTraces
    self.traces.each do |t|
      t.destroy
    end
  end
    
end
